package cn.wolfcode.wolf2w.business.repository;

import cn.wolfcode.wolf2w.business.domain.Strategy;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author : 邓风来
 * @date : 2025/9/30 11:44
 */
@Repository
public class StrategyRepository {

    @Autowired
    private RestHighLevelClient client;
    public static final String INDEX = "strategy";
    public List<Strategy> search(String query, int size) throws IOException {
        SearchSourceBuilder ssb = new SearchSourceBuilder()
                .query(QueryBuilders
                        .multiMatchQuery(query, "title", "subTitle", "summary"))
                .size(size);
        SearchRequest request = new SearchRequest(INDEX).source(ssb);
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);

        ArrayList<Strategy> list = new ArrayList<>();
        for (SearchHit hit : response.getHits().getHits()) {
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();
            String title = sourceAsMap.get("title").toString();
            String subTitle = sourceAsMap.get("subTitle").toString();
            String summary = sourceAsMap.get("summary").toString();
            Strategy strategy = new Strategy(null,title, subTitle, summary);
            list.add(strategy);

        }
        return list;
    }
}
